package ru.fadeev.crammer.ui;

import java.awt.Insets;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

import javax.swing.JTextField;


/**
 * TableTextFieldFactory class contains functions for creating TableTextField.
 * TableTextField difference from ordinary text field is when TableTextField
 * gets focus all text doesn't get selected like in ordinary text field.
 * @author Konstantin Fadeyev
 *
 */
public class TableTextFieldFactory {

	public static JTextField createTableTextField() {
		final JTextField textField = new JTextField();
		textField.setMargin(new Insets(0,0,0,0));
		textField.setBorder(null);
		textField.addFocusListener(
    			new FocusAdapter() {
    				public void focusGained(FocusEvent e) {
    					int start = textField.getSelectionStart();
    					int end = textField.getSelectionEnd();
    					int caret = textField.getCaretPosition();
    					if((start == 0) && (start != end) && 
    							(end == textField.getText().length()) && 
    							(caret == end)) {
    						textField.setSelectionStart(end);
    					}
    				}
    			});
		return textField;
	}
	
	public static JTextField createTableTextField(final JTextField textField) {
		textField.setMargin(new Insets(0,0,0,0));
		textField.setBorder(null);
		textField.addFocusListener(
    			new FocusAdapter() {
    				public void focusGained(FocusEvent e) {
    					int start = textField.getSelectionStart();
    					int end = textField.getSelectionEnd();
    					int caret = textField.getCaretPosition();
    					if((start == 0) && (start != end) && 
    							(end == textField.getText().length()) && 
    							(caret == end)) {
    						textField.setSelectionStart(end);
    					}
    				}
    			});
		return textField;
	}
}
